﻿using System;
using System.Collections.Generic;
using System.IO;

namespace LoLHQ
{
    /// <summary>
    /// Class for managing counters records
    /// </summary>
    class LOLDb
    {
        /// <summary>
        /// Currently selected database file
        /// </summary>
        public string Filename = "db.txt";

        /// <summary>
        /// Creates a new database
        /// </summary>
        public void CreateDb()
        {
            File.WriteAllText(Filename, "");
        }

        /// <summary>
        /// Writes a db entry
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void WriteEntry(string topic, string key, string value)
        {
            value = value.Replace("\r", "^|^");
            value = value.Replace("\n", "^|^");
            if (ReadEntry(topic, key) != null)
            {
                DeleteEntry(topic, key);
            }
                
            File.AppendAllText(Filename, topic + "`" + key + "`" + value + "\r\n");
        }


        /// <summary>
        /// Deletes db entry
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="key"></param>
        public void DeleteEntry(string topic, string key)
        {
            try
            {   
                string[] lines = File.ReadAllLines(Filename);
                List<string> res = new List<string>();

                for (int i = 0; i < lines.Length; i++)
                {
                    if (!lines[i].StartsWith(topic + "`" + key))
                        res.Add(lines[i]);
                }

                File.WriteAllLines(Filename, res.ToArray());
            }
            catch
            {
            }
        }


        /// <summary>
        /// Reads db entry, or NULL if not found
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public string ReadEntry(string topic, string key)
        {
            try
            {
                string[] lines = File.ReadAllLines(Filename);
                foreach (string line in lines)
                {
                    string[] stringSplit = line.Split('`');
                    if (String.Compare(topic, stringSplit[0]) == 0 && String.Compare(key, stringSplit[1]) == 0)
                    {
                        return stringSplit[2].Replace("^|^", "\n");
                    }
                }
                
                return null;
            }
            catch
            {
                return null;
            }
        }


        /// <summary>
        /// Gets all entries related to specified champions
        /// </summary>
        /// <param name="key"></param>
        /// <param name="user1"></param>
        /// <param name="user2"></param>
        /// <returns></returns>
        public List<ChampCountersListStruct> GetCounters(string key, string user1, string user2)
        {   
            List<ChampCountersListStruct> list = new List<ChampCountersListStruct>();

            if (!File.Exists(Filename))
                return list;

            string[] lines = File.ReadAllLines(Filename);
            foreach (string line in lines)
            {
                string[] stringSplit = line.Split('`');

                // if key matches - check the entry
                if (String.Compare(key, stringSplit[1]) == 0)
                {
                    // get all champion names
                    string[] tmp = stringSplit[0].Split('|');

                    // solo/jungle
                    if (key != "d")
                    {   
                        if (tmp[0].CompareTo(user1) == 0)
                        {
                            list.Add(new ChampCountersListStruct() { Name = tmp[1], DisplayName = tmp[1], Score = Int32.Parse(stringSplit[2].Split('|')[0]) });
                        }
                        else if (tmp[1].CompareTo(user1) == 0) // reverse the score
                        {
                            list.Add(new ChampCountersListStruct() { Name = tmp[0], DisplayName = tmp[0], Score = -Int32.Parse(stringSplit[2].Split('|')[0]) });
                        }
                    }
                    else
                        if (key == "d")
                        {
                            if ((tmp[0].CompareTo(user1) == 0 && tmp[1].CompareTo(user2) == 0) ||
                                (tmp[1].CompareTo(user1) == 0 && tmp[0].CompareTo(user2) == 0))
                            {
                                list.Add(new ChampCountersListStruct() { Name = tmp[2] + "/" + tmp[3], DisplayName = tmp[2] + "/" + tmp[3], Score = Int32.Parse(stringSplit[2].Split('|')[0]) });
                            }
                            else if ((tmp[2].CompareTo(user1) == 0 && tmp[3].CompareTo(user2) == 0) ||
                                (tmp[3].CompareTo(user1) == 0 && tmp[2].CompareTo(user2) == 0))
                            {
                                list.Add(new ChampCountersListStruct() { Name = tmp[0] + "/" + tmp[1], DisplayName = tmp[0] + "/" + tmp[1], Score = -Int32.Parse(stringSplit[2].Split('|')[0]) });
                            }
                        }
                }
            }

            return list;
        }

        /// <summary>
        /// Gets statistics of records
        /// </summary>
        /// <param name="total"></param>
        /// <param name="solo"></param>
        /// <param name="duo"></param>
        /// <param name="jungling"></param>
        public void GetStats(out int total, out int solo, out int duo, out int jungling)
        {
            total = solo = duo = jungling = 0;

            string[] lines = File.ReadAllLines(Filename);
            foreach (string line in lines)
            {
                if (line.Length < 10)
                    continue;

                string[] stringSplit = line.Split('`');

                if (String.Compare("s", stringSplit[1]) == 0)
                    solo++;
                else if (String.Compare("d", stringSplit[1]) == 0)
                    duo++;
                else if (String.Compare("j", stringSplit[1]) == 0)
                    jungling++;
            }

            total = solo + duo + jungling;
        }

    }
}
